/*
ehs - 2010-06-05
Flickr search

2010-06-05
----------
*/


function FlickrSearch(proxyUrl_, authToken_)
{
	var that_ = this; // required for private function support


	this.photos = new Array();


	function retrievePhotos_()
	{
		var lastPage = that_.photos.length / 50;
		var pageToRetrieve = Math.floor(lastPage + 1);
		if (pageToRetrieve == searchParams.page) {
			if (doneCallback != null)
				doneCallback();
			return;
		}
		searchParams.page = pageToRetrieve;

		$.get(proxyUrl_,
			searchParams,
			function(data, textStatus) {
				that_.onGetPhotosCompleted_(data, textStatus);
			},
			"json");
	}


	this.onGetPhotosCompleted_ = function(data, textStatus)
	{
		if (textStatus != "success" || data.stat != "ok")
			return;

		if (data.photos.photo.length > 0) {
			this.photos = this.photos.concat(data.photos.photo);
			searchCallback();
			retrievePhotos_();
		}
		else if (doneCallback != null)
			doneCallback();
	}

	// todo: only retrieve info when created
	// todo: return public object
	// todo: make client explicitly request photos with separate callback (from public object)
	// todo: wait on photo retrieval until info has been received
	// todo: *** allow custom pagination through new retrievePhotos method ***

	var searchParams = {
		method: "flickr.photos.search",
		auth_token: authToken_,
		user_id: "me",
		per_page: 50,
		extras: "date_taken,date_upload,o_dims,tags" // fixme: can we get original photo name?
	};


	function setTakenDateRange(minTakenDate, maxTakenDate)
	{
		if (minTakenDate == null || maxTakenDate == null) {
			delete searchParams.min_taken_date;
			delete searchParams.max_taken_date;
			return;
		}

		// fixme: need to ensure date is in mysql datetime format
		searchParams.min_taken_date = minTakenDate;
		searchParams.max_taken_date = maxTakenDate;
	}


	function setUploadDateRange(minUploadDate, maxUploadDate)
	{
		if (minUploadDate == null || maxUploadDate == null) {
			delete searchParams.min_upload_date;
			delete searchParams.max_upload_date;
			return;
		}

		// fixme: need to ensure date is in unix timestamp format
		searchParams.min_upload_date = minUploadDate;
		searchParams.max_upload_date = maxUploadDate;
	}
	
	
	function setTags(tags, requireAllTags)
	{
		searchParams.tags = tags;
		if (requireAllTags)
			searchParams.tag_mode =	"all";
	}


	var searchCallback = null;
	function startSearch(callback, done)
	{
		if (callback == null)
			return;

		that_.photos.length = 0;
		delete searchParams.page;
		searchCallback = callback;
		doneCallback = done;

		retrievePhotos_();
	}


	var publicObj = {
		getPhotos : function() { return that_.photos; },
		setTakenDateRange : setTakenDateRange,
		setUploadDateRange : setUploadDateRange,
		setTags : setTags,
		startSearch : startSearch
	};
	return publicObj;
}

